// 商品分类
import React, { useEffect, useState } from 'react'
import { getClassUp, chabgeDiy ,deleteAllcheck ,deleteCate} from '../../../api/finance'
import { Table, Space, Button, Modal, message, Switch } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { ExclamationCircleFilled } from '@ant-design/icons'
import ClassChild from './xiekunchild/ClassChild'
import ClassChildAdd from './xiekunchild/ClassChildAdd'
// 表格
interface DataType {
  key: React.Key
  categoryCreated: string
  categoryId: number
  categoryImg: string
  categoryMsg: string
  categoryName: string
  categoryNumber: number
  categoryParent: number
  categoryRec: string
  categorySort: string
  categoryStatus: string
  goodsId?: number
  id?: number
}

export default function GoodClassify() {
  const [data, setData] = useState<any>([])
  const getList = () => {
    getClassUp()
      .then((res) => {
        console.log('res=======>', res)
        setData(res.data)
        addKey(res.data)
      })
      .catch((err) => {
        console.log('err=====>', err)
      })
  }
  useEffect(() => {
    getList()
  }, [])
  // 上架下架开关
  const [checkedNum,setCheckedNum] = useState<boolean>()
  const onChange = (checked: boolean) => {
    console.log('checked ====>', checked)
    setCheckedNum(checked)
  }
  const onChange1 = (record:any) => {
    console.log('record上架=====>',record);
    chabgeDiy({
      "categoryId": record.categoryId,
      "categoryStatus": `${checkedNum ? '4' : '1'}`
    }).then((res) => {
      console.log('res上架====>', res);
      getList()
    }).catch((err) => {
      console.log('err上架====>', err);
    });
  }
  const onChange2 = (checked: boolean) => {
    console.log(`switch2 ====> ${checked}`)
  }
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'categoryId',
    },
    {
      title: '分类',
      dataIndex: 'categoryName',
    },
    {
      title: '分类图标',
      dataIndex: 'categoryImg',
    },
    {
      title: '级别',
      dataIndex: 'categoryParent',
    },
    {
      title: '商品数量',
      dataIndex: 'categoryNumber',
    },
    {
      title: '是否上架',
      dataIndex: 'categoryStatus',
      render: (_, record) => {
        return (
          <Switch
            defaultChecked={Number(record.categoryStatus) === 1}
            onChange={onChange}
            onClick={() => onChange1(record)}
          />
        )
      },
    },
    {
      title: '首页推荐',
      dataIndex: 'categoryRec',
      render: (_, record) => {
        return (
          <Switch
            defaultChecked={Number(record.categoryRec) === 1}
            onChange={onChange2}
          />
        )
      },
    },
    {
      title: '排序',
      dataIndex: 'categorySort',
    },
    {
      title: '设置',
      render: (_, record) => (
        <Space size="middle">
          <Button className="add">新增下级</Button>
          <Button className="add">查看下级</Button>
        </Space>
      ),
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space size="small">
          <Button className="add" onClick={() => redact(record)}>
            编辑
          </Button>
          <Button id="del" onClick={() => showConfirm(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ]

  const [SelectedRow, setSelectedRow] = useState()
  const rowSelection = {
    onChange: (key: any, row: DataType[]) => {
      let checkArr: any = []
      row.map((item) => {
        checkArr.push(item.categoryId)
      })
      setSelectedRow(checkArr)
      console.log('checkArr', checkArr)
    },
  }
  // 操作部分
  // （1）删除
  // 删除弹框
 // 删除弹框
 const { confirm } = Modal
 const showConfirm = (record: any) => {
   confirm({
     title: '提示:',
     icon: <ExclamationCircleFilled />,
     content: '您确定要删除这一行吗？删除后无法恢复！',
     cancelText: '取消',
     okText: '确认',
     onOk() {
       console.log('OK', record)
      //  点击确定发起请求
      deleteCate({id:record.categoryId}).then((res) => {
         console.log('res删除', res)
         getList()
       }).catch((err) => {
         console.log('err删除', err)
       });
     },
   })
 }

  //给子组件传的数据
  const [redactList, setRedactList] = useState<object | undefined>()
  // （2）编辑
  const redact = (record: any) => {
    console.log('record', record)
    setRedactList(record)
    setIsModalOpen(true)
  }

  //添加分类
  const addClass = () => {
    setIsModalOpen2(true)
  }
  // （2）添加和修改共用弹框
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false) //是否显示对话框
  const [isModalOpen2, setIsModalOpen2] = useState<boolean>(false) //是否显示对话框
  // 自定义添加修改弹框消失
  const modalClose = () => {
    setIsModalOpen(false)
  }
  const modalClose2 = () => {
    setIsModalOpen2(false)
  }

  const addKey = (data: any) => {
    data.map((item:any) => {
      item.id = Math.floor(Math.random() * 10000000000)
      return item
    })
  }
  return (
    <div>
      {/* 头部标题 */}
      <p className="head">商品分类</p>
      <div className="operationTable">
        <Button className="add" onClick={addClass}>添加分类</Button>
      </div>
      <Table
        style={{ marginTop: '50px' }}
        rowSelection={rowSelection}
        columns={columns}
        dataSource={data}
        pagination={{ pageSize: 6 }}
        rowKey={item => String(item.id)}
      />
      <ClassChild
        redactList={redactList}
        modalClose={modalClose}
        isModalOpen={isModalOpen}
        getList={getList}
      ></ClassChild>

      <ClassChildAdd
        modalClose={modalClose2}
        isModalOpen={isModalOpen2}
        getList={getList}
      ></ClassChildAdd>
    </div>
  )
}
